package study.kits.excel.easyexcel.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import study.kit.eggs.result.Result;
import study.kit.eggs.result.Results;
import study.kits.excel.easyexcel.service.upload.UploadService;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @SneakyThrows
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam(value = "file") MultipartFile file,
                         HttpServletRequest request) {
        //
        if (Objects.isNull(file) || file.isEmpty()) {
            // throw new VException(ErrCode.PARAM_EMPTY, "file");
        }
        //
        long size = file.getSize();
        log.info(">>>>>> File Size (byte): {}", size);

        //
//        print(file);
        //
        String name = ServletRequestUtils.getStringParameter(request, "name");
        log.info("name= {}", name);
        String age = ServletRequestUtils.getStringParameter(request, "age");
        log.info("age= {}", age);
        //
        uploadService.upload(file);
        return Results.ok();
    }

    void print(MultipartFile file) {
        String name = file.getName();
        String filename = file.getOriginalFilename();
        String contentType = file.getContentType();
        log.info("name= {}", name);
        log.info("filename= {}", filename);
        log.info("content_type= {}", contentType);
    }
}
